﻿@model CustomerListModel
@using System.Globalization;
@{
    var defaultGridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().DefaultGridPageSize;
    var gridPageSizes = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSizes;

    //page title
    ViewBag.Title = T("Admin.Customers.Customers").Text;
}
@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/Administration/Content/images/ico-customers.png")" alt="" />
            @T("Admin.Customers.Customers")
        </div>
        <div class="options">
            <a href="@Url.Action("Create")" class="k-button">@T("Admin.Common.AddNew")</a>
            <a href="@Url.Action("ExportXmlAll")" class="k-button">@T("Admin.Common.ExportToXml.All")</a>
            <input type="button" id="exportxml-selected" class="k-button" value="@T("Admin.Common.ExportToXml.Selected")" />
            <a href="@Url.Action("ExportExcelAll")" class="k-button">@T("Admin.Common.ExportToExcel.All")</a>
            <input type="button" id="exportexcel-selected" class="k-button" value="@T("Admin.Common.ExportToExcel.Selected")" />
        </div>
    </div>
    <table width="100%">
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchCustomerRoleIds):
            </td>
            <td class="adminData">
                @foreach (var customerRole in Model.AvailableCustomerRoles)
                {
                    <input type="checkbox" name="SearchCustomerRoleIds" value="@customerRole.Id"
                @if (Model.SearchCustomerRoleIds != null && Model.SearchCustomerRoleIds.Contains(customerRole.Id))
                {
                    <text>checked="checked"</text>
                }
                />@customerRole.Name
                    <br />
                }
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchEmail)
            </td>
        </tr>
        @if (Model.UsernamesEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchUsername):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.SearchUsername)
                </td>
            </tr>
        }
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchFirstName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchFirstName)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SearchLastName):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.SearchLastName)
            </td>
        </tr>
        @if (Model.DateOfBirthEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchDayOfBirth):
                </td>
                <td class="adminData">
                    @{
            var monthOfBirthValues = new List<SelectListItem>();
            monthOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Month").Text, Value = "0" });
            for (int i = 1; i <= 12; i++)
            {
                monthOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
            var dayOfBirthValues = new List<SelectListItem>();
            dayOfBirthValues.Add(new SelectListItem() { Text = T("Admin.Customers.Customers.List.SearchDateOfBirth.Day").Text, Value = "0" });
            for (int i = 1; i <= 31; i++)
            {
                dayOfBirthValues.Add(new SelectListItem() { Text = i.ToString(CultureInfo.InvariantCulture), Value = i.ToString(CultureInfo.InvariantCulture) });
            }
                    }
                    @Html.DropDownListFor(model => model.SearchMonthOfBirth, monthOfBirthValues)
                    @Html.DropDownListFor(model => model.SearchDayOfBirth, dayOfBirthValues)
                </td>
            </tr>
        }
        
        @if (Model.CompanyEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchCompany):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.SearchCompany)
                </td>
            </tr>
        }        
        @if (Model.PhoneEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchPhone):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.SearchPhone)
                </td>
            </tr>
        }
        @if (Model.ZipPostalCodeEnabled)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchZipPostalCode):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => model.SearchZipPostalCode)
                </td>
            </tr>
        } 
        <tr>
            <td colspan="2">
                <input type="button" id="search-customers" class="k-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
    <p>
    </p>
    <table class="adminContent">
        <tr>
            <td>
                <div id="customers-grid"></div>

                <script>
                    $(document).ready(function () {
                        $("#customers-grid").kendoGrid({
                            dataSource: {
                                type: "json",
                                transport: {
                                    read: {
                                        url: "@Html.Raw(Url.Action("CustomerList", "Customer"))",
                                        type: "POST",
                                        dataType: "json",
                                        data: additionalData
                                    }
                                },
                                schema: {
                                    data: "Data",
                                    total: "Total",
                                    errors: "Errors"
                                },
                                error: function(e) {
                                    display_kendoui_grid_error(e);
                                    // Cancel the changes
                                    this.cancelChanges();
                                },
                                pageSize: @(defaultGridPageSize),
                                serverPaging: true,
                                serverFiltering: true,
                                serverSorting: true
                            },
                            pageable: {
                                refresh: true,
                                pageSizes: [@(gridPageSizes)]
                            },
                            scrollable: false,
                            dataBound: onDataBound,
                            columns: [{
                                    field: "Id",
                                    headerTemplate: "<input id='mastercheckbox' type='checkbox'/>",
                                    headerAttributes: { style: "text-align:center" },
                                    attributes: { style: "text-align:center" },
                                    template: "<input type='checkbox' value='#=Id#' class='checkboxGroups'/>",
                                    width: 50
                                }, {
                                    field: "Id",
                                    title: "ID",
                                    width: 50
                                }, {
                                    field: "Email",
                                    title: "@T("Admin.Customers.Customers.Fields.Email")",
                                    width: 200
                                },
                                @if (Model.UsernamesEnabled)
                                {
                                    <text>{
                field: "Username",
                title: "@T("Admin.Customers.Customers.Fields.Username")",
                width: 200
            },</text>
                                }
                                {
                                    field: "FullName",
                                    title: "@T("Admin.Customers.Customers.Fields.FullName")",
                                    width: 200
                                }, {
                                    field: "CustomerRoleNames",
                                    title: "@T("Admin.Customers.Customers.Fields.CustomerRoles")",
                                    width: 200
                                }, 
            
                                @if (Model.CompanyEnabled)
                                {
                                    <text>{
                field: "Company",
                                    title: "@T("Admin.Customers.Customers.Fields.Company")",
            width: 200
        },</text>
                                }
        
                                @if (Model.PhoneEnabled)
                                {
                                    <text>{
                field: "Phone",
                    title: "@T("Admin.Customers.Customers.Fields.Phone")",
            width: 200
        },</text>
                                }
        
                                @if (Model.ZipPostalCodeEnabled)
                                {
                                    <text>{
                field: "ZipPostalCode",
                    title: "@T("Admin.Customers.Customers.Fields.ZipPostalCode")",
            width: 200
        },</text>
                                }
                            {
                                field: "Active",
                                title: "@T("Admin.Customers.Customers.Fields.Active")",
                                width: 100,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '<img src="@Url.Content("~/Administration/Content/images/")active-#=Active#.gif" />'
                            }, {
                                field: "CreatedOn",
                                title: "@T("Admin.Customers.Customers.Fields.CreatedOn")",
                                width: 200,
                                type: "date",
                                format: "{0:G}"
                            }, {
                                field: "LastActivityDate",
                                title: "@T("Admin.Customers.Customers.Fields.LastActivityDate")",
                                width: 200,
                                type: "date",
                                format: "{0:G}"
                            }, {
                                field: "Id",
                                title: "@T("Admin.Common.Edit")",
                                width: 50,
                                template: '<a href="Edit/#=Id#">@T("Admin.Common.Edit")</a>'
                            }]
                        });
                    });
                </script>

                <script type="text/javascript">

                    var selectedIds = [];

                    $(document).ready(function () {

                        //search button
                        $('#search-customers').click(function () {
                            var grid = $('#customers-grid').data('kendoGrid');
                            grid.dataSource.page(1); //new search. Set page size to 1
                            grid.dataSource.read();
                            //clear selected checkboxes
                            $('.checkboxGroups').attr('checked', false).change();
                            selectedIds = [];
                            return false;
                        });

                        $("#@Html.FieldIdFor(model => model.SearchEmail)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchUsername)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchFirstName)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchLastName)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchCompany)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchPhone)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });
                        $("#@Html.FieldIdFor(model => model.SearchZipPostalCode)").keydown(function (event) {
                            if (event.keyCode == 13) {
                                $("#search-customers").click();
                                return false;
                            }
                        });

                        $('#mastercheckbox').click(function () {
                            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
                        });

                        //wire up checkboxes.
                        $('#customers-grid').on('change', 'input[type=checkbox][id!=mastercheckbox]', function (e) {
                            var $check = $(this);
                            if ($check.is(":checked") == true) {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked == -1) {
                                    //add id to selectedIds.
                                    selectedIds.push($check.val());
                                }
                            }
                            else {
                                var checked = jQuery.inArray($check.val(), selectedIds);
                                if (checked > -1) {
                                    //remove id from selectedIds.
                                    selectedIds = $.grep(selectedIds, function (item, index) {
                                        return item != $check.val();
                                    });
                                }
                            }
                            updateMasterCheckbox();
                        });
                    });

                    function onDataBound(e) {

                        $('#customers-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
                            var currentId = $(this).val();
                            var checked = jQuery.inArray(currentId, selectedIds);
                            //set checked based on if current checkbox's value is in selectedIds.
                            $(this).attr('checked', checked > -1);
                        });

                        updateMasterCheckbox();
                    }

                    function updateMasterCheckbox() {
                        var numChkBoxes = $('#customers-grid input[type=checkbox][id!=mastercheckbox]').length;
                        var numChkBoxesChecked = $('#customers-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
                        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
                    }

                    function additionalData() {
                        var customerRoleIds = [];
                        $('[name=SearchCustomerRoleIds]:checked').each(function () {
                            customerRoleIds.push($(this).val());
                        });

                        return {
                            SearchCustomerRoleIds: customerRoleIds.join(","),
                            SearchEmail: $('#@Html.FieldIdFor(model => model.SearchEmail)').val(),
                            SearchUsername: $('#@Html.FieldIdFor(model => model.SearchUsername)').val(),
                            SearchFirstName: $('#@Html.FieldIdFor(model => model.SearchFirstName)').val(),
                            SearchLastName: $('#@Html.FieldIdFor(model => model.SearchLastName)').val(),
                            SearchDayOfBirth: $('#@Html.FieldIdFor(model => model.SearchDayOfBirth)').val(),
                            SearchMonthOfBirth: $('#@Html.FieldIdFor(model => model.SearchMonthOfBirth)').val(),
                            SearchCompany: $('#@Html.FieldIdFor(model => model.SearchCompany)').val(),
                            SearchPhone: $('#@Html.FieldIdFor(model => model.SearchPhone)').val(),
                            SearchZipPostalCode: $('#@Html.FieldIdFor(model => model.SearchZipPostalCode)').val()
                        };
                    }
                </script>
            </td>
        </tr>
    </table>
}

@*export selected (XML). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportXmlSelected", "Customer", FormMethod.Post, new { id = "export-xml-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-xml-selected-form #selectedIds').val(ids);
            $('#export-xml-selected-form').submit();
            return false;
        });
    });

</script>

@*export selected (Excel). We don't use GET approach because it's limited to 2K-4K chars and won't work for large number of entities*@
@using (Html.BeginForm("ExportExcelSelected", "Customer", FormMethod.Post, new { id = "export-excel-selected-form" }))
{
    <input type="hidden" id="selectedIds" name="selectedIds" value="" />
}
<script type="text/javascript">

    $(document).ready(function () {
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            var ids = selectedIds.join(",");
            $('#export-excel-selected-form #selectedIds').val(ids);
            $('#export-excel-selected-form').submit();
            return false;
        });
    });

</script>